package com.thiscc.sum.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.thiscc.sum.common.MongoDBManager;
import com.thiscc.sum.constance.TableName;
import com.thiscc.sum.service.IWorkService;
import com.thiscc.sum.utils.JSONUtils;

/**
 * 工作首页webservice接口
 * @author admin
 *
 */
public class WorkService implements IWorkService {

    //数据库操作对象
    private MongoDBManager db = MongoDBManager.getInstance();
    public static Log log = LogFactory.getLog(WorkService.class);

    /**
     * 设置工作列表是否显示
     * @param showList 需要的显示的功能
     * @param hideList 需要的隐藏的功能
     * @return
     */
    public boolean setShow(String uuid, String showList, String hideList) {

        try {
            JSONArray showArray = JSONArray.fromObject(showList);
            JSONArray hideArray = JSONArray.fromObject(hideList);

            for (int i = 0; i < showArray.size(); i++) {
                //条件
                DBObject conditionDB = new BasicDBObject();
                conditionDB.put("uuid", uuid);
                conditionDB.put("pid", showArray.get(i));
                //修改数据
                DBObject updateDB = new BasicDBObject();
                updateDB.put("show", "1");

                db.update(TableName.T_WORK, conditionDB, updateDB);
            }

            for (int i = 0; i < hideArray.size(); i++) {
                //条件
                DBObject conditionDB = new BasicDBObject();
                conditionDB.put("uuid", uuid);
                conditionDB.put("pid", hideArray.get(i));
                //修改数据
                DBObject updateDB = new BasicDBObject();
                updateDB.put("show", "0");

                db.update(TableName.T_WORK, conditionDB, updateDB);
            }
        } catch (Exception e) {
            log.error(e.getLocalizedMessage(), e);
        }
        return false;
    }

    /**
     * 查询工作列表接口
     * @return
     */
    public String getWorkList(String uuid) {

        //查询置顶的数据
        DBObject conditionDB = new BasicDBObject();
        conditionDB.put("uuid", uuid);
        conditionDB.put("show", "1");
        conditionDB.put("insteadTop", "1");

        List<DBObject> topList = db.find(TableName.T_WORK, conditionDB);

        //查询非置顶数据
        conditionDB.put("insteadTop", "0");
        List<DBObject> notTopList = db.find(TableName.T_WORK, conditionDB);

        JSONObject json = new JSONObject();

        json.put("top", JSONArray.fromObject(topList));

        json.put("notTop", JSONArray.fromObject(notTopList));

        return json.toString();
    }

    /**
     * 置顶
     * @return
     */
    public boolean setTop(String uuid, String functionid) {

        try {
            //条件
            DBObject conditionDB = new BasicDBObject();
            conditionDB.put("uuid", uuid);
            conditionDB.put("pid", functionid);
            //修改数据
            DBObject updateDB = new BasicDBObject();
            updateDB.put("insteadTop", "1");
            updateDB.put("time", new Date());

            db.update(TableName.T_WORK, conditionDB, updateDB);
            return true;
        } catch (Exception e) {
            log.error(e.getLocalizedMessage(), e);
        }
        return false;
    }

    /**
     * 取消置顶
     * @return
     */
    public boolean setNotTop(String uuid, String functionid) {

        try {
            //条件
            DBObject conditionDB = new BasicDBObject();
            conditionDB.put("uuid", uuid);
            conditionDB.put("pid", functionid);
            //修改数据
            DBObject updateDB = new BasicDBObject();
            updateDB.put("insteadTop", "0");

            db.update(TableName.T_WORK, conditionDB, updateDB);
            return true;
        } catch (Exception e) {
            log.error(e.getLocalizedMessage(), e);
        }
        return false;
    }

    /**
     * 增加功能消息条数
     * @return
     */
    public boolean addMsgCount(String uuid, String functionid) {

        try {
            //条件
            DBObject conditionDB = new BasicDBObject();
            conditionDB.put("uuid", uuid);
            conditionDB.put("pid", functionid);

            //修改数据
            DBObject updateDB = new BasicDBObject();
            updateDB.put("count", 1);

            db.updateInt(TableName.T_WORK, conditionDB, updateDB);
            return true;
        } catch (Exception e) {
            log.error(e.getLocalizedMessage(), e);
        }
        return false;
    }

    /**
     * 减少功能消息条数
     * @return
     */
    public boolean reduceMsgCount(String uuid, String functionid) {

        try {
            //条件
            DBObject conditionDB = new BasicDBObject();
            conditionDB.put("uuid", uuid);
            conditionDB.put("pid", functionid);

            //修改数据
            DBObject updateDB = new BasicDBObject();
            updateDB.put("count", -1);

            db.updateInt(TableName.T_WORK, conditionDB, updateDB);
            return true;
        } catch (Exception e) {
            log.error(e.getLocalizedMessage(), e);
        }
        return false;
    }

    @Override
    public boolean modifyWork(String data) {

        boolean ret = true;

        JSONObject jsonObj = JSONObject.fromObject(data);
        String uuid = jsonObj.getString("uuid");

        JSONArray foradd = jsonObj.optJSONArray("proNew");
        JSONArray fordel = jsonObj.optJSONArray("delProduct");

        //准备要增加的数据
        List<DBObject> addList = new ArrayList<DBObject>();
        if (foradd != null)
            for (int i = 0; i < foradd.size(); i++) {

                JSONObject obj = foradd.getJSONObject(i);
                DBObject proNew = new BasicDBObject();
                proNew.put("pid", JSONUtils.getString(obj, "pid"));
                proNew.put("name", JSONUtils.getString(obj, "name"));
                proNew.put("uuid", uuid);
                proNew.put("ico", JSONUtils.getString(obj, "pid") + ".png");
                proNew.put("time", new Date());
                proNew.put("insteadTop", "0");
                proNew.put("bedding", "");
                proNew.put("show", "1");
                proNew.put("count", 0);
                proNew.put("remark", JSONUtils.getString(obj, "remark"));
                proNew.put("url", JSONUtils.getString(obj, "url"));
                proNew.put("groupId", "");
                addList.add(proNew);
            }

        //执行增加、删除操作
        try {
            db.insertBatch(TableName.T_WORK, addList);

            //准备要删除的数据
            DBObject delCondtion = new BasicDBObject();
            if (fordel.size() > 0 && fordel != null) {
                delCondtion.put("uuid", uuid);

                for (int i = 0; i < fordel.size(); i++) {

                    JSONObject jso_work = fordel.getJSONObject(i);
                    String s_pid = JSONUtils.getString(jso_work, "pid");
                    delCondtion.put("pid", s_pid);

                    db.delete(TableName.T_WORK, delCondtion);
                }

            }
        } catch (Exception e) {
            ret = false;
            log.error(e.getLocalizedMessage(), e);
        }

        return ret;
    }

    @Override
    public String queryWork(String uuid) {

        DBObject condition = new BasicDBObject();
        condition.put("uuid", uuid);

        try {

            //数据库操作
            List<DBObject> workList = db.find(TableName.T_WORK, condition);

            if (workList.size() < 1) {
                return "";
            }
            return workList.toString();

        } catch (Exception e) {
            log.error("sum_webervice接口查询work产品出错", e);
        }

        return null;
    }

    @Override
    public String deleteWork(String uuid) {

        String flg = "";
        int delsum = 0;
        DBObject obj = new BasicDBObject();
        DBObject objDate = new BasicDBObject();
        obj.put("uuid", uuid);
        try {
            // 根据uuid删除attention数据
            if (db.delete(TableName.SUMMARIZE_ATTENTION, obj)) {
                delsum += 1;
            }
            // 根据uuid删除content数据
            if (db.delete(TableName.SUMMARIZE_CONTENT, obj)) {
                delsum += 1;
            }
            // 根据UUID查询content表consignee数组记录并移除
            List<DBObject> contentList = new ArrayList<DBObject>();
            contentList.add(obj);
            objDate.put("consignee.uuid", uuid);
            if (contentList != null) {
                contentList = db.find(TableName.SUMMARIZE_CONTENT, objDate);
                if (contentList != null) {
                    db.updateRemoveBatch(TableName.SUMMARIZE_CONTENT, obj, contentList);
                }
            }

            // 根据uuid删除group数据
            if (db.delete(TableName.SUMMARIZE_GROUP, obj)) {
                delsum += 1;
            }
            // 根据uuid删除reciever数据
            if (db.delete(TableName.SUMMARIZE_RECIEVER, obj)) {
                delsum += 1;
            }

            // 根据UUID查询reciever表reciever数组记录并移除
            List<DBObject> recieverList = new ArrayList<DBObject>();
            recieverList.add(obj);
            objDate.put("reciever.uuid", uuid);
            if (recieverList != null) {
                recieverList = db.find(TableName.SUMMARIZE_RECIEVER, objDate);
                if (recieverList != null) {
                    db.updateRemoveBatch(TableName.SUMMARIZE_RECIEVER, obj, recieverList);
                }
            }
            // 根据uuid删除replay数据
            if (db.delete(TableName.SUMMARIZE_REPLAY, obj)) {
                delsum += 1;
            }
            // 根据uuid删除share数据
            if (db.delete(TableName.SUMMARIZE_SHARE, obj)) {
                delsum += 1;
            }

            // 根据uuid删除work数据
            if (db.delete(TableName.T_WORK, obj)) {
                delsum += 1;
            }
            if (delsum > 0) {
                flg = "删除成功";
            } else {
                flg = "sumWork中不包含该数据";
            }
        } catch (Exception e) {
            // TODO: handle exception
            flg = "删除失败";
            e.printStackTrace();
            return flg;
        }
        return flg;
    }
}
